import {Component, OnInit} from '@angular/core';

// 当做一个服务
import {HttpClient, HttpHeaders} from '@angular/common/http'

// 引入服务
import {HttpServiceService} from '../service/http-service.service'

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {

  public list: any[] = [];

  public postDate: object = {};

  constructor(public http: HttpClient, public httpService: HttpServiceService) {
  }

  ngOnInit() {
  }

  // get请求
  getData() {
    // https:httpbin.org/get
    // https://httpbin.org/post
    // params: {
    //         name: "coderwhy",
    //         age: 18
    //       }
    let api = 'http://a.itying.com/api/productlist';
    this.http.get(api).subscribe((res: any) => {
      console.log(res);
      this.list = res.result;
    })
  }

  // post请求
  doLogin() {
    const httpOptions = {
      headers: new HttpHeaders({"content-type": 'application/json'})
    };
    let url = 'https://httpbin.org/post';
    this.http.post(url, {name: '小笑残虹', age: 18}, httpOptions).subscribe((res: any) => {
      console.log(res);
      this.postDate = res.json;
    })
  }

  // jsonp 跨域请求
  getJsonp() {

    /*
    * http://a.itying.com/api/productlist?callback=xxx
    * http://a.itying.com/api/productlist?cb=xxx
    * */
    let api = 'http://a.itying.com/api/productlist';
    this.http.jsonp(api, 'callback').subscribe((res: any) => {
      console.log(res);
      this.list = res.result;
    })
  }

  // axios get方法获取数据
  axiosGetData() {
    let api = 'http://a.itying.com/api/productlist';
    this.httpService.axiosGet(api).then((res: any) => {
      console.log(res);
      this.list = res.data.result;
    })
  }

}
